package com.hb.core.config;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Arrays;

public class MybatisPlusConfig {

    protected String[] mybatisPlusLocations;

    public MybatisPlusConfig(String... locations) {
        if (ArrayUtil.isEmpty(locations)) {
            locations = new String[]{"classpath:mapper/*Mapper.xml"};
        }
        mybatisPlusLocations = locations;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver loader = new PathMatchingResourcePatternResolver();

        // 加载mybatis的xml映射文件
        Resource[] root = {};
        for (String mapperLocation : mybatisPlusLocations) {
            int len = root.length;
            Resource[] resource = loader.getResources(mapperLocation);
            root = Arrays.copyOf(root, root.length + resource.length);
            System.arraycopy(resource, 0, root, len, resource.length);
        }

        sqlSessionFactoryBean.setMapperLocations(root);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(true);
        sqlSessionFactoryBean.setConfiguration(configuration);

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 添加分页功能

        sqlSessionFactoryBean.setTypeHandlersPackage("com.hb.core.config.handler");

        sqlSessionFactoryBean.setPlugins(
                interceptor
        );
        return sqlSessionFactoryBean.getObject();
    }

}
